package com.zyf.wjy.service;

import com.zyf.wjy.dao.SalesRecordDao;
import com.zyf.wjy.entity.SalesRecord;
import com.zyf.wjy.util.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 销售记录服务类
 */
@Service
public class SalesRecordService {
    
    @Autowired
    private SalesRecordDao salesRecordDao;
    
    @Autowired
    private ProductService productService;
    
    /**
     * 查询所有销售记录
     */
    public List<SalesRecord> findAll() {
        return salesRecordDao.findAll();
    }
    
    /**
     * 根据ID查询
     */
    public SalesRecord findById(Long id) {
        return salesRecordDao.findById(id);
    }
    
    /**
     * 根据产品ID查询
     */
    public List<SalesRecord> findByProductId(Long productId) {
        return salesRecordDao.findByProductId(productId);
    }
    
    /**
     * 根据客户名称查询
     */
    public List<SalesRecord> findByCustomerName(String customerName) {
        return salesRecordDao.findByCustomerName(customerName);
    }
    
    /**
     * 保存销售记录
     */
    public SalesRecord save(SalesRecord record) {
        if (record.getId() == null) {
            record.setSalesCode(CodeGenerator.generateSalesCode());
            record.setCreateTime(LocalDateTime.now());
            
            // 计算总金额
            if (record.getQuantity() != null && record.getPrice() != null) {
                record.setTotalAmount(record.getQuantity() * record.getPrice());
            }
        }
        
        SalesRecord saved = salesRecordDao.save(record);
        
        // 更新产品库存
        if (saved.getProductId() != null && saved.getQuantity() != null) {
            productService.stockOut(saved.getProductId(), saved.getQuantity());
        }
        
        return saved;
    }
    
    /**
     * 删除销售记录
     */
    public boolean deleteById(Long id) {
        return salesRecordDao.deleteById(id);
    }
}

